//
//  SearchBarViewController.m
//  BeautyClother
//
//  Created by dllo on 15/9/5.
//  Copyright (c) 2015年 宋爽. All rights reserved.
//

#import "SearchBarViewController.h"
#import "AsyncConnection.h"
#import "define.h"
#import "AFNetworking.h"
#import "StoreLayout.h"
#import "UIImageView+WebCache.h"
#import "SuitCell.h"
#import "ItemsModel.h"
#import "DataBase.h"
#import "CollectionController.h"
#import "ItemDataBase.h"
#import "MBProgressHUD.h"
#import "Reachability.h"
#import "MJRefresh.h"

int m = 18;
@interface SearchBarViewController ()<UISearchBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UISearchBar *searchBar;

@property (nonatomic, retain) NSMutableArray *array;

@property (nonatomic, retain) AFHTTPRequestOperationManager *man;

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, assign) CGFloat offHeight;
@property (nonatomic, assign) CGFloat offWidth;

@property (nonatomic, retain) StoreLayout *flow;
@property (nonatomic, retain) ItemsModel *model;
@property (nonatomic, retain) MBProgressHUD *mb;

@end

@implementation SearchBarViewController

- (void)dealloc
{
    [_collection release];
    [_flow release];
    [_model release];
    [_mb release];
    [_man release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.model = [[ItemsModel alloc]init];
    // Do any additional setup after loading the view.
    self.array = [NSMutableArray array];
    self.man = [[AFHTTPRequestOperationManager alloc] init];

    
    self.view.backgroundColor = [UIColor whiteColor];
    self.searchBar = [[UISearchBar alloc] init];

    
    CGFloat offwidth = [UIScreen mainScreen].bounds.size.width / 375;
    self.searchBar.frame = CGRectMake(0, 0, 250 * offwidth, 50);
    
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"🍓 搜索搭配";
    
    self.navigationItem.titleView = self.searchBar;
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.flow = [[StoreLayout alloc]init];
    
    [self createOtherCollection];
    self.offWidth = [[UIScreen mainScreen]bounds].size.width / 375;
    self.offHeight = [[UIScreen mainScreen]bounds].size.height / 667;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"f.png"] style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor darkGrayColor];
    // Do any additional setup after loading the view.

}

- (void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)handleData
{
    BOOL net = [SearchBarViewController judgeConnect];
    if (net) {
        
    
//    http://esearch.hichao.com/query?gc=appstore&gf=iphone&gn=mxyc_ip&gv=6.3.0&gi=2CC19978-A0E5-49F2-9719-59DC5EDE6BBB&gs=640x1136&gos=8.4&access_token=I7OQDp90vxcyU2lFmyZBxJa2u_dbL6JfRqSfkDT127E&type=star&q=%E6%98%8E%E6%98%9F&flag=
    NSDictionary *dic = @{@"gc":@"appstore",
                          @"gf":@"iphone",
                          @"gn":@"mxyc_ip",
                          @"gv":@"6.3.0",
                          @"gi":@"2CC19978-A0E5-49F2-9719-59DC5EDE6BBB",
                          @"gs":@"640x1136",
                          @"gos":@"8.4",
                          @"access_token":@"I7OQDp90vxcyU2lFmyZBxJa2u_dbL6JfRqSfkDT127E",
                          @"q":self.searchBar.text,
                          @"sort":@"all",
                          @"flag":@"",
                          @"type":@"star"};
   
    
    [self.man GET:Search_List parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *arr = [[responseObject objectForKey:@"data"] objectForKey:@"items"];
        if (arr.count != 0) {
            
        
        [self.array addObjectsFromArray: arr];
        self.flow.dicArray = self.array;
        [self.collection reloadData];
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"没有搜索到, 请重新搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
            self.searchBar.text = @"";
            [self.mb removeFromSuperview];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"解析出错");
    }];
        
    }else
    {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"没有搜索到, 请重新搜索" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        self.searchBar.text = @"";
        [self.mb removeFromSuperview];
    }

}

- (void)addFooter
{
    __block SearchBarViewController *actionVC = self;
   
    [self.collection addFooterWithCallback:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSDictionary *dic = @{@"gc":@"appstore",
                                  @"gf":@"iphone",
                                  @"gn":@"mxyc_ip",
                                  @"gv":@"6.3.0",
                                  @"gi":@"2CC19978-A0E5-49F2-9719-59DC5EDE6BBB",
                                  @"gs":@"640x1136",
                                  @"gos":@"8.4",
                                  @"access_token":@"I7OQDp90vxcyU2lFmyZBxJa2u_dbL6JfRqSfkDT127E",
                                  @"q":self.searchBar.text,
                                  @"sort":@"all",
                                  @"flag":[NSString stringWithFormat:@"%d", m],
                                  @"type":@"star"};
            
            [self.man GET:Search_List parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSArray *arr = [[responseObject objectForKey:@"data"] objectForKey:@"items"];
                if (arr.count == 0) {
                    [self.collection footerEndRefreshing];
                } else
                {
                    [self.array addObjectsFromArray:arr];
                    _flow.dicArray = self.array;
                    [actionVC.collection reloadData];
                   
                }
                 m += 18;
              
                [self.collection footerEndRefreshing];
            }
                  failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  
                  }];
            
        }
                       );
    }];
    

}

//http://esearch.hichao.com/query?gc=appstore&gf=iphone&gn=mxyc_ip&gv=6.3.3&gi=D8580E8A-8527-4EBB-B8AF-A3D8172A0099&gs=750x1334&gos=9.0.2&access_token=&type=star&q=%E5%AE%8B%E6%99%BA%E5%AD%9D&flag=



+ (BOOL)judgeConnect
{
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus sta = [reach currentReachabilityStatus];
    if (sta == NotReachable) {
        return NO;
    }else{
        return YES;
    }
}


- (void)createOtherCollection
{
    [self.collection removeFromSuperview];
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0 , 64 , self.view.frame.size.width, self.view.frame.size.height - 112) collectionViewLayout:_flow];
    
    self.collection.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:.1 alpha:0.1];
    
    self.collection.delegate = self;
    self.collection.dataSource = self;
    [self.collection registerClass:[SuitCell class] forCellWithReuseIdentifier:@"aaaa"];
    [self.view addSubview:self.collection];
    [self addFooter];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.array.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.mb removeFromSuperview];
    SuitCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"aaaa" forIndexPath:indexPath];
    
    NSString *pic = [[[[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"picUrl"]componentsSeparatedByString:@"?"]objectAtIndex:0];
    [cell.image sd_setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"zw.jpg"]];
    
    [cell.like setTitle:[[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"collectionCount"] forState:UIControlStateNormal];
    [cell.like setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
    
    cell.like.tag = indexPath.item;
    cell.like.selected = NO;
    [cell.like addTarget:self action:@selector(shoucang:) forControlEvents:UIControlEventTouchUpInside];
      cell.title.textColor = [UIColor darkGrayColor];
    cell.title.font = [UIFont systemFontOfSize:15];
    
    cell.title.text = [[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"description"];
    if ([cell.title.text rangeOfString:self.searchBar.text].location != NSNotFound) {
        cell.title.attributedText = [self changeWithString:cell.title.text light:self.searchBar.text];
    }
    
    
    [cell.share setTitle:[[[self.array objectAtIndex:indexPath.item]objectForKey:@"component"]objectForKey:@"price"] forState:UIControlStateNormal];
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    cell.backgroundColor = [UIColor whiteColor];
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSDictionary *dic = [self.array objectAtIndex:indexPath.item];
    CollectionController *coll = [[CollectionController alloc]init];
    coll.aid = [[[dic objectForKey:@"component"]objectForKey:@"action"]objectForKey:@"id"];
    coll.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:coll animated:YES];
    [coll release];
}

- (void)shoucang:(UIButton *)button
{
    
    [DataBase dataBaseOpen];
    [self.model setValuesForKeysWithDictionary:[[self.array objectAtIndex:button.tag]objectForKey:@"component"]];
    
    if (button.selected == YES) {
        [DataBase dataBaseOpen];
        [ItemDataBase deleteWithid:self.model.iid];
        NSInteger i = [[[[self.array objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"collectionCount"] integerValue];
        [button setTintColor:[UIColor darkGrayColor]];
        [button setImage:[UIImage imageNamed:@"heart.png"] forState:UIControlStateNormal];
        
        [button setTitle:[NSString stringWithFormat:@"%ld", i] forState:UIControlStateNormal];
        
    }
    if (button.selected == NO) {
        self.model.iid = [[[self.array objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"id"];
        self.model.desc = [[[self.array objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"description"];
        self.model.width = [[[self.array objectAtIndex:button.tag]objectForKey:@"width"]floatValue];
        self.model.height = [[[self.array objectAtIndex:button.tag]objectForKey:@"height"]floatValue];
        [ItemDataBase insertWithModel:self.model];
        
        [button setImage:[UIImage imageNamed:@"sheart.png"] forState:UIControlStateNormal];
        [button setTintColor:[UIColor clearColor]];
        NSInteger i = [[[[self.array objectAtIndex:button.tag]objectForKey:@"component"]objectForKey:@"collectionCount"] integerValue];
        
        i = i + 1;
        
        [button setTitle:[NSString stringWithFormat:@"%ld", i] forState:UIControlStateNormal];
        
    }
    if (button.selected == YES) {
        button.selected = NO;
    }else
    {
        button.selected = YES;
    }
    
}

- (NSMutableAttributedString *)changeWithString:(NSString *)string light:(NSString *)light
{
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:string];
    for (int i = 0; i < attributeString.length - light.length + 1; i ++) {
        if ([[string substringWithRange:NSMakeRange(i, light.length)]isEqualToString:light]) {
            // 设置高亮
            NSRange range = NSMakeRange(i, light.length);
            [attributeString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255/255 green:0 blue:255/255 alpha:0.8] range:range];
            [attributeString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:range];
            
        }
    }
    return attributeString;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.mb = [[MBProgressHUD alloc]initWithView:[[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]];
    [self.view addSubview:self.mb];
    [self.mb show:YES];
    self.mb.labelText = @"大好人的程序正在为您搜索";
    self.mb.labelFont = [UIFont systemFontOfSize:12];
    
    [searchBar resignFirstResponder];
    [self handleData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
